package deleteface.bank.jqsoft.cn.deleteface.http;



import com.trello.rxlifecycle.ActivityEvent;

import java.lang.ref.WeakReference;

import deleteface.bank.jqsoft.cn.deleteface.base.AbstractActivity;

import rx.Observable;

import rx.schedulers.Schedulers;
import rx.android.schedulers.AndroidSchedulers;
/**
 *
 * 基类presenter
 */
public abstract class BasePresenter<V> {
    private WeakReference<V> weakRefView;

    protected BasePresenter() {
    }

    public void attach(V view) {
        weakRefView = new WeakReference<>(view);
    }

    public void detach() {
        if (isAttach()) {
            weakRefView.clear();
            weakRefView = null;
        }
    }

    public V obtainView() {
        return isAttach() ? weakRefView.get() : null;
    }

    protected boolean isAttach() {
        return weakRefView != null &&
                weakRefView.get() != null;
    }

    protected V getView() {
        return weakRefView.get();
    }

    protected AbstractActivity mActivity;


    public BasePresenter(AbstractActivity act) {
        this.mActivity = act;
    }


    /**
     * Activity网络请求通用方法
     *
     * @param observable 被观察者模式
     * @param subscriber 订阅者
     * @param <T> 泛型
     */
    protected <T> void addActSubscribe(Observable<T> observable, MySubscriber<T> subscriber) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mActivity.<T>bindUntilEvent(ActivityEvent.DESTROY))//绑定生命周期，防止内存泄露
                .subscribe(subscriber);
    }



}
